package logger

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"
)

// EbbFlowEnhancedLogger EbbFlow增强日志器
type EbbFlowEnhancedLogger struct {
	nodeID       int
	perfLogger   *EnhancedPerformanceLogger
	componentTracker *ComponentTracker
	analyzer     *ComponentLatencyAnalyzer
	logDir       string
}

// NewEbbFlowEnhancedLogger 创建EbbFlow增强日志器
func NewEbbFlowEnhancedLogger(nodeID int, logDir string) (*EbbFlowEnhancedLogger, error) {
	// 创建增强性能日志记录器
	perfLogger, err := NewEnhancedPerformanceLogger(nodeID, logDir, 30*time.Second)
	if err != nil {
		return nil, fmt.Errorf("failed to create enhanced performance logger: %v", err)
	}

	// 创建组件跟踪器
	componentTracker := NewComponentTracker(perfLogger)

	// 创建分析器
	analyzer := NewComponentLatencyAnalyzer(perfLogger)

	return &EbbFlowEnhancedLogger{
		nodeID:           nodeID,
		perfLogger:       perfLogger,
		componentTracker: componentTracker,
		analyzer:         analyzer,
		logDir:           logDir,
	}, nil
}

// LogPerformance 记录性能指标
func (eel *EbbFlowEnhancedLogger) LogPerformance(tps float64, latency int64, epoch int, batchSize int, txSize int) {
	eel.perfLogger.RecordMetrics(tps, latency, epoch, batchSize, txSize)
}

// GetComponentTracker 获取组件跟踪器
func (eel *EbbFlowEnhancedLogger) GetComponentTracker() *ComponentTracker {
	return eel.componentTracker
}

// GeneratePerformanceReport 生成性能报告
func (eel *EbbFlowEnhancedLogger) GeneratePerformanceReport() string {
	return eel.analyzer.GeneratePerformanceReport()
}

// Stop 停止日志记录器
func (eel *EbbFlowEnhancedLogger) Stop() {
	eel.perfLogger.Stop()
	
	// 导出指标
	if err := eel.perfLogger.ExportMetrics(); err != nil {
		log.Printf("Failed to export metrics: %v", err)
	}
	
	// 导出组件延迟
	if err := eel.perfLogger.ExportComponentLatencies(); err != nil {
		log.Printf("Failed to export component latencies: %v", err)
	}
	
	// 生成性能报告
	report := eel.GeneratePerformanceReport()
	reportFile := filepath.Join(eel.logDir, fmt.Sprintf("node_%d_performance_report.txt", eel.nodeID))
	if err := os.WriteFile(reportFile, []byte(report), 0644); err != nil {
		log.Printf("Failed to write performance report: %v", err)
	}
}

// GetMetrics 获取性能指标
func (eel *EbbFlowEnhancedLogger) GetMetrics() []EnhancedPerformanceMetrics {
	return eel.perfLogger.GetMetrics()
}

// GetComponentLatencies 获取组件延迟
func (eel *EbbFlowEnhancedLogger) GetComponentLatencies() map[string][]ComponentLatency {
	return eel.perfLogger.GetComponentLatencies()
}

// CreateEnhancedAWSSetup 创建增强的AWS设置
func (eel *EbbFlowEnhancedLogger) CreateEnhancedAWSSetup() error {
	// 创建配置文件
	configPath := filepath.Join(eel.logDir, "enhanced_aws_config.yaml")
	config := `aws:
  regions:
    - us-east-1
    - us-west-2
    - eu-west-1
  
  instance_types:
    small: t3.medium
    medium: t3.large
    large: t3.xlarge
    xlarge: t3.2xlarge
  
  ami_ids:
    us-east-1: ami-0c02fb55956c7d316  # Amazon Linux 2
    us-west-2: ami-0c02fb55956c7d316
    eu-west-1: ami-0c02fb55956c7d316
  
  security_groups:
    us-east-1: sg-12345678
    us-west-2: sg-87654321
    eu-west-1: sg-11223344
  
  key_pairs:
    us-east-1: ebbflow-aws-key
    us-west-2: ebbflow-aws-key
    eu-west-1: ebbflow-aws-key

benchmark:
  default_settings:
    nodes: 4
    duration: 60
    batch_size: 100
  
  test_scenarios:
    - name: "small_cluster"
      nodes: 4
      instance_type: t3.medium
      duration: 30
    
    - name: "medium_cluster"
      nodes: 7
      instance_type: t3.large
      duration: 60
    
    - name: "large_cluster"
      nodes: 16
      instance_type: t3.xlarge
      duration: 120
    
    - name: "stress_test"
      nodes: 32
      instance_type: t3.2xlarge
      duration: 300

monitoring:
  collect_metrics: true
  metrics_interval: 10
  log_level: 1
  component_tracking: true
  enhanced_logging: true`

	if err := os.WriteFile(configPath, []byte(config), 0644); err != nil {
		return fmt.Errorf("failed to write enhanced config file: %v", err)
	}

	// 创建增强的README文件
	readmePath := filepath.Join(eel.logDir, "ENHANCED_README.md")
	readme := `# EbbFlow增强性能监控系统

## 概述
这个系统提供了EbbFlow协议的全面性能监控，包括各个组件的延迟跟踪和性能分析。

## 功能特性
- ✅ 整体性能监控 (TPS, 延迟, Epoch)
- ✅ 组件级别延迟跟踪 (RBC, ABA, CommonCoin, CBR, ProofChain)
- ✅ 实时性能分析
- ✅ 详细的性能报告
- ✅ AWS部署支持

## 组件监控

### RBC (可靠广播)
- RBC_SEND: 广播发送延迟
- RBC_ECHO: Echo消息延迟
- RBC_READY: Ready消息延迟
- RBC_DELIVER: 消息投递延迟

### ABA (异步拜占庭协议)
- ABA_BVAL: BVAL消息延迟
- ABA_AUX: AUX消息延迟
- ABA_CONF: CONF消息延迟
- ABA_FINAL: FINAL消息延迟

### CommonCoin (公共硬币)
- COMMON_COIN_GEN: 硬币生成延迟
- COMMON_COIN_COMBINE: 份额组合延迟

### CBR (条件广播)
- CBR_DISTRIBUTE: 分发延迟
- CBR_REPLY: 回复延迟
- CBR_READY: Ready延迟

### ProofChain (证明链)
- PROOF_CHAIN_GEN: 证明生成延迟
- PROOF_CHAIN_VERIFY: 证明验证延迟
- PROOF_CHAIN_LINK: 链链接延迟

## 使用方法

### 1. 基本使用
```go
// 创建增强日志器
logger, err := NewEbbFlowEnhancedLogger(nodeID, "logger")
if err != nil {
    log.Fatal(err)
}

// 获取组件跟踪器
tracker := logger.GetComponentTracker()

// 跟踪RBC操作
rbcTracker := tracker.TrackRBC("RBC_SEND", instanceID, round, epoch)
// ... 执行RBC操作 ...
rbcTracker.Finish(true, "")

// 跟踪ABA操作
abaTracker := tracker.TrackABA("ABA_BVAL", instanceID, round, epoch)
// ... 执行ABA操作 ...
abaTracker.Finish(true, "")
```

### 2. 性能分析
```go
// 生成性能报告
report := logger.GeneratePerformanceReport()
fmt.Println(report)

// 获取组件延迟
latencies := logger.GetComponentLatencies()
```

### 3. 停止和导出
```go
// 停止日志器
logger.Stop()
// 自动导出所有指标和报告
```

## 输出文件
- node_*_enhanced_performance.log: 增强性能日志
- node_*_enhanced_metrics.json: 增强指标JSON
- node_*_component_latencies.json: 组件延迟JSON
- node_*_performance_report.txt: 性能分析报告

## 性能评估标准
- Excellent: 成功率≥95%, 平均延迟<100ms
- Good: 成功率≥90%, 平均延迟<200ms
- Fair: 成功率≥80%, 平均延迟<500ms
- Poor: 其他情况
`

	if err := os.WriteFile(readmePath, []byte(readme), 0644); err != nil {
		return fmt.Errorf("failed to create enhanced README: %v", err)
	}

	fmt.Printf("Enhanced AWS setup created in: %s\n", eel.logDir)
	return nil
}
